import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

import { viteMockServe } from 'vite-plugin-mock'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
	// 获取各种环境下的所需变量  mode： 当前所在环境 process.cwd() 文件根目录，index.html
	const env = loadEnv(mode, process.cwd())
	return {
		plugins: [
			vue(),
			createSvgIconsPlugin({
				iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
				symbolId: 'icon-[dir]-[name]'
			}),
			viteMockServe({
				// 保证开发阶段可以使用mock数据
				localEnabled: command === 'serve'
			})
		],
		resolve: {
			alias: {
				'@': fileURLToPath(new URL('./src', import.meta.url))
			}
		},
		// 全局scss样式
		css: {
			preprocessorOptions: {
			  scss: {
				additionalData: `
				  @use "./src/styles/variable.scss" as *;
				`,
			  },
			},
		  },
		// 解决开跨域问题
		server: {
			proxy: {
				[env.VITE_APP_BASE_API]: {
					target: env.VITE_SERVE,
					changeOrigin: true,
					rewrite: path => path.replace(/^\/api/, '')
				}
			}
		}
	}
})
